﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using DBUtil;
using DBCook.Models;
using DBCook.Common;
using System.IO;
using DotNetCommon.Extensions;

namespace DBCook.Utils
{
    public static class SessionExtensions
    {
        public static T Get<T>(this ISession session, string key)
        {
            var bytes = session.Get(key);
            var json = System.Text.Encoding.UTF8.GetString(bytes);
            return JsonConvert.DeserializeObject<T>(json);
        }

        public static void Set<T>(this ISession session, string key, T value)
        {
            var json = JsonConvert.SerializeObject(value);
            session.Set(key, System.Text.Encoding.UTF8.GetBytes(json));
        }

        public static DBAccess GetDb(this ISession session, string guid = null)
        {
            //var dbinfo = Get<DbInfo>(session, Consts.CURRENT_DB);
            //return DBFactory.CreateDB(dbinfo.Type, $"Data Source={dbinfo.Addr};Initial Catalog={dbinfo.Db};User={dbinfo.User};Password={dbinfo.Pwd};");

            if(guid.IsNullOrEmptyOrWhiteSpace())
            {
                guid = Startup.HttpContext.Request.Headers["db-guid"].ToString();
                if (guid.IsNullOrEmptyOrWhiteSpace())
                {
                    guid = Startup.HttpContext.Request.Query["guid"].ToString();
                }
            }
            
            var str = File.ReadAllText(Path.Combine(Startup.WebRoot, "config", "connections.json"));
            var connections = JsonConvert.DeserializeObject<List<DbInfo>>(str);
            var dbinfo = connections.FirstOrDefault(i => i.Guid == guid);
            return DBFactory.CreateDB(dbinfo.Type, $"Data Source={dbinfo.Addr};Initial Catalog={dbinfo.Db};User={dbinfo.User};Password={dbinfo.Pwd};");
        }
    }
}
